package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/youkelike/gateway/core/lib"
	"github.com/youkelike/gateway/tcp_server"
)

// var (
// 	addr     = ":7002"
// 	endpoint = "test_tcp_service/7002"
// )

var serviceName = "test_tcp_service"

type tcpHandler struct {
}

func (t *tcpHandler) ServeTCP(ctx context.Context, src net.Conn) {
	in := make([]byte, 30)
	for {
		n, err := src.Read(in)
		if n == 0 || err != nil {
			fmt.Println("err occur", err)
			break
		}
		if n == 4 {
			s := strings.TrimSpace(string(in[:4]))
			fmt.Println("==", s, len(s))
			if s == "quit" {
				fmt.Println("client quit")
				break
			}
		}

		fmt.Println("recv: ", string(in), n)
		in = append(in, '\n')
		src.Write(in)
		in = make([]byte, 30)
	}

	// in := "tcpHandler\n"
	// reader := bufio.NewReader(src)
	// for {
	// 	in, _ = reader.ReadString('\n')
	// 	fmt.Println("recv: ", in)

	// 	if in == "" || strings.TrimSpace(in) == "quit" {
	// 		return
	// 	}
	// 	src.Write([]byte(in))
	// }
}

// tcp 服务器测试，需要启动 etcd 服务
func main() {
	// BACKEND_SCHEME 格式： "tcpbackend,7002,50"
	sc := strings.Split(os.Getenv("BACKEND_SCHEME"), ",")
	if len(sc) != 3 {
		log.Fatal("BACKEND_SCHEME should be set")
	}

	addr := fmt.Sprintf("0.0.0.0:%s", sc[1])
	log.Println("Starting tcpserver at " + addr)
	tcpServ := tcp_server.Server{
		Addr:    addr,
		Handler: &tcpHandler{},
	}

	etcdServer := os.Getenv("ETCD_SERVER")
	if len(etcdServer) == 0 {
		log.Fatal("ETCD_SERVER should be set")
	}
	registry, err := lib.NewEtcdRegistry([]string{etcdServer}, time.Duration(5))
	if err != nil {
		panic(err)
	}

	// 格式："test_tcp_service/7002"
	endpoint := fmt.Sprintf("%s/%s", serviceName, sc[1])
	// 注册格式： "tcpbackend:7002,50"
	err = registry.Register(endpoint, fmt.Sprintf("%s:%s,%s", sc[0], sc[1], sc[2]))
	if err != nil {
		panic(err)
	}

	go func() {
		tcpServ.ListenAndServe()
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	err = registry.Unregister(context.Background(), endpoint)
	if err != nil {
		fmt.Println("unregister")
		panic(err)
	}
	err = registry.Close()
	if err != nil {
		panic(err)
	}

	//代理测试
	//rb := load_balance.LoadBanlanceFactory(load_balance.LbWeightRoundRobin)
	//rb.Add("127.0.0.1:6001", "40")
	//proxy := proxy.NewTcpLoadBalanceReverseProxy(&tcp_middleware.TcpSliceRouterContext{}, rb)
	//tcpServ := tcp_proxy.TcpServer{Addr: addr, Handler: proxy,}
	//fmt.Println("Starting tcp_proxy at " + addr)
	//tcpServ.ListenAndServe()

	//redis服务器测试
	//rb := load_balance.LoadBanlanceFactory(load_balance.LbWeightRoundRobin)
	//rb.Add("127.0.0.1:6379", "40")
	//proxy := proxy.NewTcpLoadBalanceReverseProxy(&tcp_middleware.TcpSliceRouterContext{}, rb)
	//tcpServ := tcp_proxy.TcpServer{Addr: addr, Handler: proxy,}
	//fmt.Println("Starting tcp_proxy at " + addr)
	//tcpServ.ListenAndServe()

	//http服务器测试:
	//缺点对请求的管控不足,比如我们用来做baidu代理,因为无法更改请求host,所以很轻易把我们拒绝
	//rb := load_balance.LoadBanlanceFactory(load_balance.LbWeightRoundRobin)
	//rb.Add("127.0.0.1:2003", "40")
	////rb.Add("www.baidu.com:80", "40")
	//proxy := proxy.NewTcpLoadBalanceReverseProxy(&tcp_tcp_middleware.TcpSliceRouterContext{}, rb)
	//tcpServ := tcp_proxy.TcpServer{Addr: addr, Handler: proxy,}
	//fmt.Println("tcp_proxy start at:" + addr)
	//tcpServ.ListenAndServe()

	//websocket服务器测试:缺点对请求的管控不足
	//rb := load_balance.LoadBanlanceFactory(load_balance.LbWeightRoundRobin)
	//rb.Add("127.0.0.1:2003", "40")
	//proxy := proxy.NewTcpLoadBalanceReverseProxy(&tcp_middleware.TcpSliceRouterContext{}, rb)
	//tcpServ := tcp_proxy.TcpServer{Addr: addr, Handler: proxy,}
	//fmt.Println("Starting tcp_proxy at " + addr)
	//tcpServ.ListenAndServe()

	//http2服务器测试:缺点对请求的管控不足
	//rb := load_balance.LoadBanlanceFactory(load_balance.LbWeightRoundRobin)
	//rb.Add("127.0.0.1:3003", "40")
	//proxy := proxy.NewTcpLoadBalanceReverseProxy(&tcp_middleware.TcpSliceRouterContext{}, rb)
	//tcpServ := tcp_proxy.TcpServer{Addr: addr, Handler: proxy,}
	//fmt.Println("Starting tcp_proxy at " + addr)
	//tcpServ.ListenAndServe()
}
